<template>
  <div class="switch-box"
       :style="`width:${width};height:${height}`">
    <template v-if="list.length">
      <transition name="fade">
        <img :src="activeItem.url"
             :style="`width:${width};height:${height}`"
             key="img1"
             v-if="bool"
             alt="">
        <img :src="activeItem.url"
             :style="`width:${width};height:${height}`"
             key="img2"
             v-else
             alt="">
      </transition>
    </template>
    <template v-else>
      <div class="placeholder"
           :style="`width:${width};height:${height}`">
        暂无内容展示
      </div>
    </template>
  </div>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '200px'
    }
  },
  data () {
    return {
      activeItem: {
        url: ''
      },
      activeIndex: -1,
      bool: true,
      timer: 0
    }
  },
  watch: {
    'list.length': {
      handler: function () {
        this.adTime()
      }
    }
  },
  beforeDestroy () {
    clearTimeout(this.timer)
  },
  methods: {
    test () {
      this.bool = !this.bool
      let index = this.activeIndex
      index++
      if (index > this.list.length - 1) {
        index = 0
      }
      this.activeIndex = index
    },
    adTime () {
      clearTimeout(this.timer)
      let index = this.activeIndex

      if (index !== -1) {
        this.bool = !this.bool
      }

      index++
      if (index > this.list.length - 1) {
        index = 0
      }
      const item = this.list[index]
      this.activeIndex = index
      this.activeItem = item

      this.timer = setTimeout(() => {
        this.adTime()
      }, item.time * 1000 + 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.placeholder {
  width: 100%;
  height: 200px;
  background-color: #e6e6e6;
  color: #828282;
  font-size: 0.2px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.switch-box {
  width: 100%;
  height: 200px;
  position: relative;
  // background-color: aquamarine;
  overflow: hidden;
  > img {
    width: 100%;
    height: 200px;
    position: absolute;
    top: 0;
    left: 0;
  }
}

.fade-enter,
.fade-leave-to {
  transform: translateX(500px);
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.8s;
}

.fade-leave-active {
  transform: translateX(-200px);
}

// .fade-enter-to,
// .fade-leave {
//   opacity: 1;
// }
</style>
